package com.example.xiaomaotv;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;

public class RegisterActivity extends AppCompatActivity {
    private EditText usernameEdit;
    private EditText accountEdit;
    private EditText passwordEdit;
    private MySQL helper;
    private SQLiteDatabase database;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_register);

        initViews();
        initDatabase();
    }
    private void initViews() {
        usernameEdit = findViewById(R.id.et_username);
        accountEdit = findViewById(R.id.et_account);
        passwordEdit = findViewById(R.id.et_password);
    }
    private void initDatabase() {
        helper = new MySQL(RegisterActivity.this, "XiaoMaoTv", null, 1);
        database = helper.getWritableDatabase();
    }
    //点击注册
    public void BT_Register_onClick(View view) {
        //获取用户输入的用户名和账号密码
        String usernameInput = usernameEdit.getText().toString();
        String accountInput = accountEdit.getText().toString();
        String passwordInput = passwordEdit.getText().toString();
        //搜索数据库中与输入账号相同的数据
        Cursor cursor = database.query("user",null,"account=?",new String[]{accountInput},null,null,null);
        if (usernameInput.isEmpty() || passwordInput.isEmpty() || accountInput.isEmpty()) {
            showToast("用户名、账号和密码不能为空 (!_!)");
        } else if (passwordInput.length() < 8) {
            showToast("为安全考虑，密码至少8位(!_!)");
        } else if (cursor.getCount()==0){
            //未注册过
            ContentValues values = new ContentValues();
            values.put("username",usernameInput);
            values.put("account",accountInput);
            values.put("password",passwordInput);
            database.insert("user",null,values);
            showToast("注册成功 (^_^)\n 可以直接登录");
            finish();
        }else{
            //账号存在
            showToast( "             注册失败 (@_@)\n账号已存在，请无重复注册");
        }
    }
    //点击取消
    public void BT_Cancel_onClick(View view) {
        finish();
    }
    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}